package com.example.demo.exception;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e){
        log.error("handleException==",e);
        return ResponseEntity.ok("操作失败：" + e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity handleBindException(BindException e){
        log.error("handleException==",e);
        String msg = e.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(";"));
        return ResponseEntity.ok(msg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("handleException==",e);
        String msg = e.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(";"));
        return ResponseEntity.ok(msg);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity handleConstraintViolationException(ConstraintViolationException e){
        log.error("handleException==",e);
        String msg = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
        return ResponseEntity.ok(msg);
    }


































}
